package com.lh.user.controller;

import com.lh.user.pojo.UserDo;
import com.lh.user.service.IUserService;
import org.hibernate.validator.constraints.Length;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

/**
 * @author liuhe
 * @date 2020/07/02
 */
@RestController
@Validated
public class UserController {

    private final IUserService iUserService;

    public UserController(IUserService iUserService) {
        this.iUserService = iUserService;
    }

    @GetMapping("/check/{type}/{data}")
    public ResponseEntity<Boolean> checkParams(@PathVariable @NotNull Integer type, @PathVariable @NotNull String data) {
        Boolean validData = this.iUserService.checkParams(type, data);
        if (null == validData) {
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.ok(validData);
    }

    /**
     * 发送验证码
     * Content-Type: application/x-www-form-urlencoded
     */
    @PostMapping("code")
    public ResponseEntity<Boolean> sendVerifyCode(String phone) {
        Boolean validData = this.iUserService.sendSmsCode(phone);
        if (null == validData || !validData) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @PostMapping("register")
    public ResponseEntity<Void> register(@Validated UserDo user, @RequestParam("code") String code) {
        Boolean boo = this.iUserService.register(user, code);
        if (boo == null || !boo) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping("query")
    public ResponseEntity<UserDo> queryUser(
            @RequestParam("username") @Length(min = 4, max = 30, message = "用户名只能在4~30之前") String username,
            @RequestParam("password") @Length(min = 4, max = 30, message = "密码只能在4~30之前") String password) {
        UserDo boo = this.iUserService.queryUser(username, password);
        if (boo == null) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        return ResponseEntity.ok(boo);
    }
}
